$(function () {
    var $ipTax = $('#fmMember input[name=tax]');
    $ipTax.focus(function () {
        if ($(this).val() == '0') {
            $(this).val('');
        }
    });
    $ipTax.bind('input propertychange', function () {
        var nowVal = $(this).val();
        var saleDiscount = $('#fmMember input[name=sale_discount]').val();
        var total = parseFloat(nowVal) + parseFloat(saleDiscount);
        $('#fmMember input[name=total]').val(total);
    });

    var $rbPayType = $('#fmMember input[name=pay_type]');
    $rbPayType.each(function () {
        $(this).click(function () {
            // console.log($(this).val());
            if ($(this).val() == '挂账') {
                $('#fmMember input[name=pay_result]').each(function () {
                    if ($(this).val() == '0') {
                        $(this).attr('checked', 'checked');
                    } else {
                        $(this).removeAttr('checked');
                    }
                })
            }
        })
    });

    var $tbClients = $('#tbClients'), $pager = $('#tbClientsPager');
    var $tbCars = $('#tbCars'), $pager = $('#tbCarsPager');

    // 调出模态框的时候去加载数据
    $('#modal-tbClients').on('show.bs.modal', function (e) {
        //加载数据
        $tbClients.jqGrid({
            url: modifyWork_urls.getClients,
            datatype: 'json',
            mttype: 'post',
            colNames: ['姓名', '地址', '电话', '操作'],
            colModel: [
                {name: 'name', index: 'name', width: 100, align: 'center'},
                {name: 'address', index: 'address', width: 200, align: 'center'},
                {name: 'phone', index: 'phone', width: 160, align: 'center'},
                {
                    name: 'id', index: 'id', width: 50, align: 'center',
                    formatter: function (value, options, obj) {
                        return '<a style="cursor:pointer;" onclick="modifyWork.chooseClient(' + value + ',\'' + obj.name + '\');">选择</a>';
                    }
                },
            ],
            height: 'auto',
            pager: '#tbClientsPager',
            // viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 40],
            autowidth: true
        });
        // 隐藏水平方向滚动条
        $tbClients.closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
    });

});

modifyWork = {
    // 查询客户
    search: function () {
        var $fmQuery = $('.fmClientQuery-hook');
        var param = ittaoli.serializeObject($fmQuery);
        $('#tbClients').jqGrid('setGridParam', {
            postData: {q: JSON.stringify(param)},
            page: 1
        }).trigger("reloadGrid");
    },
    // 清空查询条件
    searchNull: function () {
        $('.fmClientQuery-hook input').val('');
        var param = {};
        $('#tbClients').jqGrid('setGridParam', {
            postData: {q: JSON.stringify(param)},
            page: 1
        }).trigger("reloadGrid");
    },
    // 添加客户
    addClient: function (obj) {
        var $fmAdd = $('.fmClientAdd-hook');
        var param = ittaoli.serializeObject($fmAdd);
        param.id = 0;

        if (param.name == '') {
            bootbox.alert('客户姓名不能为空!');
            return;
        }
        if (!ittaoli.regs.phone.test(param.phone)) {
            bootbox.alert('手机号码格式不正确!');
            return;
        }

        $(obj).button('loading');
        $.post(addworksingleform_urls.addClient, {param: JSON.stringify(param)}, function (data) {
            if (data > 0) {
                $('#fmWork input[name=client_name]').val(param.name);
                $('#fmWork input[name=client_id]').val(data);
                $('#tbClients').jqGrid().trigger('reloadGrid');
                $('#modal-tbClients').modal('hide');
            } else {
                bootbox.alert('保存失败！');
            }
            $(obj).button('reset');
            $fmAdd[0].reset();
        })
    },
    // 选择客户
    chooseClient: function (id, name) {
        $('#fmWork input[name=client_id]').val(id);
        $('#fmWork input[name=client_name]').val(name);
        $('#modal-tbClients').modal('hide');
    },
    nextTab: function () {
        $("#checksTab").click();
    },
    // 保存工单数据
    saveWork: function (obj) {
        var param = ittaoli.serializeObject($('#fmWork'));
        var check = ittaoli.serializeObject($('#fmCheck'));
        var server = ittaoli.serializeObject($('#fmServer'));

        param.care = check.care;
        param.cover = check.cover;
        param.propose = check.propose;

        delete check.care;
        delete check.cover;
        delete check.propose;

        // var member=ittaoli.serializeObject($('#fmMember'));

        // $.extend(param,member);
        param.check_result = JSON.stringify(check);

        if (param.propose == '') {
            bootbox.alert('请填写服务建议！');
            return;
        }
        if (param.care == '') {
            bootbox.alert('请填写保养建议！');
            return;
        }
        if (param.cover == '') {
            bootbox.alert('请填写售后保单！');
            return;
        }
        if (server.repairman_id == null) {
            bootbox.alert('请选择维修技师！');
            $("#serversTab").click();
            return;
        }

        var $trs = $('.tbServer tr');
        if ($trs.length == 1) {
            bootbox.alert('请添加服务项目！');
            $("#serversTab").click();
            return;
        }

        var tbServer = [];
        for (var i = 1, len = $trs.length - 1; i < len; i++) {
            tbServer.push({
                gnum: $trs.eq(i).find('td').eq(0).text(),
                name: $trs.eq(i).find('td').eq(1).text(),
                price: $trs.eq(i).find('td').eq(2).text(),
                num: $trs.eq(i).find('td').eq(3).text(),
                sum: $trs.eq(i).find('td').eq(4).text()
            });
        }

        $(obj).button('loading');

        $.post(modifyWork_urls.modifyWork, {
            param: JSON.stringify(param),
            server: JSON.stringify(server),
            tbServer: JSON.stringify(tbServer)
        }, function (data) {
            if (data > 0) {
                bootbox.alert("保存成功！");
                setTimeout(function () {
                    location.href = modifyWork_urls.mainPage;
                }, 1000);
            } else {
                bootbox.alert('保存失败！');
            }
            $(obj).button('reset');
        })
    },
    recharge: function () {
        $('#modal-fmRecharge').modal('show');
    },
    doCharge: function (obj) {
        var money = $('#fmMember input[name=car_moneyleft]').val();
        var param = ittaoli.serializeObject($('#fmRecharge'));
        param.car_num = $('#fmWork input[name=car_num]').val();
        if (param.car_num == '') {
            bootbox.alert('无车牌，请先去完善车辆信息！');
            return;
        }
        if (!ittaoli.regs.int.test(param.charge)) {
            bootbox.alert('充值金额请输入整数！');
            return;
        }
        $(obj).button('loading');
        $.post(modifyWork_urls.doRecharge, {param: JSON.stringify(param)}, function (data) {
            if (data > 0) {
                bootbox.alert("充值成功！");
                $('#fmMember input[name=car_moneyleft]').val(parseFloat(money) + parseFloat(param.charge));
                $('#modal-fmRecharge').modal('hide');

            } else {
                bootbox.alert('充值失败！');
            }
            $(obj).button('reset');
            $('#fmRecharge')[0].reset();
        })
    }
};